from net import Network
import numpy as np

input_nodes = 784  # 28x28
hidden_nodes = 200
output_nodes = 10  # 10 个数字类别
learning_rate = 0.1

n = Network(input_nodes, hidden_nodes, output_nodes, learning_rate)
n.load_weights("trained_model")  # 直接加载，跳过训练

# 加载测试数据集并评估模型准确率
def load_and_test_model(model, test_file="data_set/mnist_test.csv"):
    """
    加载测试集并对模型进行测试
    :param model: 训练好的 Network 模型实例
    :param test_file: 测试集文件路径
    :return: 准确率
    """
    test_inputs = []
    test_targets = []
    correct_count = 0
    total_count = 0

    with open(test_file, 'r') as f:
        for line in f:
            all_value = line.strip().split(',')
            # 处理输入：像素值归一化到 [0.01, 1.0]
            scaled_input = (np.asfarray(all_value[1:]) / 255.0 * 0.99) + 0.01
            test_inputs.append(scaled_input)

            # 真实标签（数字 0-9）
            correct_label = int(all_value[0])
            test_targets.append(correct_label)

    print(f"Loaded {len(test_inputs)} test samples.")

    # 转换为 NumPy 数组
    test_inputs = np.array(test_inputs)

    # 逐个测试
    for i in range(len(test_inputs)):
        input_data = test_inputs[i]
        # 使用模型预测
        output = model.predict(input_data)
        # 获取预测标签（最大输出值的索引）
        predicted_label = np.argmax(output)
        correct_label = test_targets[i]

        if predicted_label == correct_label:
            correct_count += 1
        total_count += 1

    accuracy = correct_count / total_count
    print(f"Test Accuracy: {accuracy:.4f} ({correct_count}/{total_count})")
    return accuracy

# 开始测试
accuracy = load_and_test_model(n, "data_set/mnist_test.csv")

